//
//  PhotoViewController.m
//  Diary
//
//  Created by lanou3g on 15/12/22.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "PhotoViewController.h"
#import "ImageCollectionViewCell.h"
#import "ShowPhotoViewController.h"
#import "VIPhotoView.h"
#import "AppDelegate.h"
#import "Photo.h"
#import "LineLayout.h"
@interface PhotoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate>

{
    
    UICollectionView *_collectionView;
    UIButton *_deleteButton;
    NSInteger deleteIndexPath;
    NSString *imagePath;
    UICollectionViewFlowLayout *layout;
    
    UIButton *_deleteButton1;
}

@property(nonatomic,strong)NSMutableArray *array;

@end

@implementation PhotoViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //UICollectionView
    [self imageCollectionViewCell];
    
    //添加照片和编辑按钮
    [self addPhoto];
    
    //从数据库中取出照片
    [self showPhoto];
    
    array1 = [NSMutableArray array];
  

}



- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    //从数据库中取出照片
    [self showPhoto];
}

//UICollectionView
- (void)imageCollectionViewCell{
    

    
    LineLayout *layout = [[LineLayout alloc] init];
    
    //3.创建CollectionView
    _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    
    UILongPressGestureRecognizer *longGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGRAction:)];
    longGR.delegate = self;
    [_collectionView addGestureRecognizer:longGR];
    
    
    //4.添加父视图
    [self.view addSubview:_collectionView];
    
    
    _deleteButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _deleteButton.frame = CGRectMake(40, 0, 30, 30);
  
    [_deleteButton addTarget:self action:@selector(delegateAction:) forControlEvents:UIControlEventTouchUpInside];
    [_deleteButton setBackgroundImage:[UIImage imageNamed:@"删除.png"] forState:UIControlStateNormal];
    
    _deleteButton1 = [UIButton buttonWithType:UIButtonTypeSystem];
    _deleteButton1.frame = CGRectMake(80, 0, 30, 30);
    
    [_deleteButton1 addTarget:self action:@selector(tapGRAction) forControlEvents:UIControlEventTouchUpInside];
    [_deleteButton1 setBackgroundImage:[UIImage imageNamed:@"退出.png"] forState:UIControlStateNormal];
    
    //5.遵守协议 实现方法
    //设置代理
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    //注册标记
   [_collectionView registerClass:[ImageCollectionViewCell class] forCellWithReuseIdentifier:@"ImageCell"];

    
}

//添加照片按钮
- (void)addPhoto{
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"添加.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction)];
    
    
    UIBarButtonItem *buttomCom =[[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain  target:self action:@selector(combinationWithImage)];
    
    self.navigationItem.leftBarButtonItems = @[buttomCom,leftItem];
    
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

//添加照片按钮事件
- (void)leftItemAction{

    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets) {
        
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
    
}


- (void)combinationWithImage{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


//编辑按钮事件
- (void)rightItemAction{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"长按照片可删除单张" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *playAlert1 = [UIAlertAction actionWithTitle:@"全部删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.navigationItem.rightBarButtonItem.title = @"删除";
        
        
        //提示是否全部删除
        [self allDeleteContent];
        
    }];
    UIAlertAction *allDeleteAlert1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.navigationItem.rightBarButtonItem.title = @"编辑";
    }];
    
    [alertVC addAction:playAlert1];
    [alertVC addAction:allDeleteAlert1];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

//提示是否全部删除
- (void)allDeleteContent{
    
    UIAlertController *alertVC1 = [UIAlertController alertControllerWithTitle:@"是否全部删除" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *allDeleteAlert = [UIAlertAction actionWithTitle:@"全部删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        //全部删除
        [self allDelete];
    }];
    
    UIAlertAction *allDeleteAlert1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.navigationItem.rightBarButtonItem.title = @"编辑";
    }];
    
    
    [alertVC1 addAction:allDeleteAlert];
    [alertVC1 addAction:allDeleteAlert1];
    [self presentViewController:alertVC1 animated:YES completion:nil];
}


#pragma mark - 协议方法 － UICollectionViewDataSource
//必须实现的
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.photoArray.count;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //1.创建cell

    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPath];
 
    
    cell.imageView.image = [UIImage imageWithData:self.photoArray[indexPath.row]];
   
    
    //返回cell
    return cell;
    
}

//从数据库中取出照片
- (void)showPhoto{
    
   
        
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    self.photoArray = [NSMutableArray array];
    self.photoArrayStr = [NSMutableArray array];
    //创建搜索请求对象，并且指明所有的数据类型
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Photo"];
    NSArray *objcArray = [app.managedObjectContext executeFetchRequest:request error:nil];
    
    for (Photo *photo in objcArray) {
        
    [self.photoArray addObject:photo.photo];
    [self.photoArrayStr addObject:photo.number];
  
    }
    
            
 
        //刷新界面
    [_collectionView reloadData];
    
}



#pragma mark - 协议方法 － UICollectionViewDelegate
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    ShowPhotoViewController *showPhotoVC = [[ShowPhotoViewController alloc] init];
    UINavigationController *showPhotoNC = [[UINavigationController alloc] initWithRootViewController:showPhotoVC];
    showPhotoNC.modalTransitionStyle = 2;
    
    UIImage *image = [UIImage imageWithData:self.photoArray[indexPath.row]];
    showPhotoVC.photo1 = image;
    
    [self presentViewController:showPhotoNC animated:YES completion:nil];
    
}


#pragma mark - 协议方法 － UIGestureRecognizerDelegate

- (void)longGRAction:(UILongPressGestureRecognizer *)gr{

                NSIndexPath *indexPath = [_collectionView indexPathForItemAtPoint:[gr locationInView:_collectionView]];
                UICollectionViewCell *cell = [_collectionView cellForItemAtIndexPath:indexPath];
                _deleteButton.hidden = NO;
                [cell addSubview:_deleteButton];
                deleteIndexPath = indexPath.row;
    
    _deleteButton1.hidden = NO;
    [cell addSubview:_deleteButton1];
}

- (void)tapGRAction{
    
    _deleteButton.hidden = YES;
    _deleteButton1.hidden = YES;
}

//全部删除
- (void)delegateAction:(UIButton *)sender{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
      
   
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Photo"];
        
    NSPredicate *cata = [NSPredicate predicateWithFormat:@"number = %@",_photoArrayStr[deleteIndexPath]];//获取当前行的内容(数据库中的)
        request.predicate = cata;
        NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
        
        for (Photo *photo in array) {
            [app.managedObjectContext deleteObject:photo];
        }
        
        if ([app.managedObjectContext hasChanges]) {
            [app.managedObjectContext save:nil];
        }
        
    _deleteButton1.hidden = YES;
    

    [self viewDidLoad];
    
    
}


- (void)allDelete{
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Photo"];
    
    NSPredicate *cata = [NSPredicate predicateWithFormat:@"number > 0"];//获取当前行的内容(数据库中的)
    request.predicate = cata;
    NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
    
    for (Photo *photo in array) {
        [app.managedObjectContext deleteObject:photo];
    }

    [self viewDidLoad];

}



/// User finish picking photo，if assets are not empty, user picking original photo.
/// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;

    for (int i = 0; i<photos.count; i++) {
        
        _imageData = UIImageJPEGRepresentation(photos[i], 0.5);
        
        Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:app.managedObjectContext];
        photo.photo = self.imageData;
        
        NSString *str = [NSString stringWithFormat:@"%@",self.imageData];
        photo.number = str;
        
        //保存照片数据
        [app saveContext];

    }
    
    [_collectionView reloadData];
    
}




@end
